(use 'clojure.contrib.duck-streams
     'readerManager)

(import '(java.net Socket ServerSocket)
        '(java.io PrintWriter BufferedReader InputStreamReader))


(def *port* 3003)
(def file-name "clientP.clj")
(def route "./")

(defn serialize
	"Converts structures into strings"
	[data]
	(binding[*print-dup* true]
  		(print-str data))
)

(defn selectAll
  "Gets all the records that are not deleted to the client"
  [database]
  (get-records(.concat route (.concat database ".db"))))

(defn select-all
  "sends the records"
  [database output]
  (let [records (serialize (selectAll database))]
    (.println output records)
    (.flush output)
    )
)

(defn create
  "Gets the data from the client and pass it to the database manager to create a new record"
  [database data]
  (new-values (.concat route (.concat database ".db")) data))

(defn delete
  "Gets the record to delete from the client and pass it to the database manager to delete a record"
  [database RecNo]
  (erase (.concat route (.concat database ".db")) RecNo))

(defn create-new
  "Creates a new record in the database"
  [data output]
  (let [[database dict] (read-string data)]
    (create database dict)
    )
)

(defn delete-rec
  "The record at the specified line in the database"
  [data output]
  (let [[database recno] (read-string data)]
    (delete database recno)
    )
)

(defn pManager
  "Manages the petitions from the client, executing the requeste operation"
  [_ socket]
  (with-open [input (BufferedReader. (InputStreamReader. (.getInputStream socket)))
	      output (PrintWriter. (.getOutputStream socket))]
      (let [database (.readLine input)
	  action (.readLine input)]
       (when (.equals action "select")
	(.flush output)
	(println (select-all database output)))
      (when (.equals action "create")
	(.flush output)
	(create-new database output))
      (when (.equals action "delete")
	(.flush output)
	(delete-rec database output))
  )
 )
)
    
(defn start
  []  
  (let [
        server       (ServerSocket. *port*)
        agent         (agent nil)]
    (loop []
      (println "Establishing conection...")      
      (let [socket (.accept server)]  
        (send-off agent pManager socket))        
      (recur))))

(start)
